package com.xxmw.transaction.service.app.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxmw.transaction.common.entity.P;
import com.xxmw.transaction.common.utils.bourse.HuobiUtil;
import com.xxmw.transaction.controller.server.TransactionWebsocketServer;
import com.xxmw.transaction.enumeration.BourseEnum;
import com.xxmw.transaction.enumeration.TopicEnum;
import com.xxmw.transaction.mapper.app.SymbolMapper;
import com.xxmw.transaction.model.app.Symbol;
import com.xxmw.transaction.service.app.SymbolService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 交易所api
 * @author luowenliang
 * @since 2020/2/14 15:59
 */
@Service
@Slf4j
public class SymbolServiceImpl extends ServiceImpl<SymbolMapper, Symbol> implements SymbolService {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public P<Symbol> pageList(int pageNum, int pageSize, String name) {
        QueryWrapper<Symbol> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");

        queryWrapper.eq(StringUtils.isNotBlank(name), "name", name);

        IPage<Symbol> page = new Page<>(pageNum, pageSize);
        this.page(page, queryWrapper);
        return new P<>(page.getTotal(), page.getRecords());
    }

    @Override
    public List<Symbol> findByQuoteCurrency(String currency) {
        QueryWrapper<Symbol> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        queryWrapper.eq( "quote_currency", currency);
        return list(queryWrapper);
    }

    @Override
    public Symbol getBuyName(String name) {
        QueryWrapper<Symbol> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name);
        return getOne(queryWrapper);
    }

    @Override
    public boolean hasSymbol(String baseCurrency, String quoteCurrency) {
        String name = baseCurrency.toLowerCase() +  quoteCurrency.toLowerCase();
        String rvName = new StringBuilder(name).reverse().toString();

        QueryWrapper<Symbol> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", name).or().eq("name", rvName);

        return null != getOne(queryWrapper);
    }

    @Override
    public Set<String> quoteCurrency() {
        return baseMapper.quoteCurrency();
    }

    @Override
    public Set<Symbol> listByBourse(Integer bourseId) {
        return baseMapper.listByBourse(bourseId);
    }

    @Override
    public void cacheSymbolDayOpenPrice() {
        Set<Symbol> symbols = listByBourse(BourseEnum.HUOBI.getValue());
        if (null != symbols && symbols.size() > 0) {
            Map<String, String> map = new HashMap<>(symbols.size());
            symbols.forEach(symbol -> map.put(symbol.getName(), HuobiUtil.dayOpen(symbol.getName())));
            redisTemplate.opsForHash().putAll(SYMBOL_DAY_OPEN_PRICE, map);
        }
    }

    @Override
    public void pushSymbolInfo(String symbol, String close) {
        if (StringUtils.isNotBlank(close)) {
            BigDecimal price = new BigDecimal(close);
            Object o = redisTemplate.opsForHash().get(SYMBOL_DAY_OPEN_PRICE, symbol);
            if (null != o) {
                String dayOpen = (String) o;
                BigDecimal open = new BigDecimal(dayOpen);
                BigDecimal v = price.subtract(open).divide(open, 4, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal(100));

                ConcurrentHashMap<Long, TransactionWebsocketServer> serverMap = TransactionWebsocketServer.getServer();

                Map<String, Object> map = new HashMap<>(16);
                map.put("symbol", symbol);
                map.put("close", close);
                map.put("gains", v.stripTrailingZeros().toPlainString());

                if (!serverMap.isEmpty()) {
                    serverMap.forEach((id, server) -> {
                        //订阅了发送消息
                        if (server.isSubscribed(TopicEnum.SYMBOL_REALTIME_INFO_TOPIC.getDesc())) {
                            server.senObject(map);
                        }
                    });
                }
            }
        }
    }
}
